package kz.kstu.scantest.business.common.util.comparator;

import kz.kstu.scantest.business.entity.data.FormData;
import org.apache.log4j.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Comparator;

/**
 * @author Filipp_Stankevich
 *         created: 08.10.11 22:55
 */
public class FormDataComparator implements Comparator<FormData> {

    private static final Logger LOGGER = Logger.getLogger(FormDataComparator.class);

    private String methodName;
    private boolean isAscending;

    public FormDataComparator(String methodName) {
        this(methodName, true);
    }


    public FormDataComparator(String methodName, boolean isAscending) {
        this.methodName = methodName;
        this.isAscending = isAscending;
    }

    @Override
    public int compare(FormData o1, FormData o2) {
        if (o1 == null) {
            return o2 == null ? 0 : -1;
        }

        if (o2 == null) {
            return 1;
        }

        Comparable firstObject = null;
        Comparable secondObject = null;

        try {
            Method method = FormData.class.getMethod(methodName);
            firstObject = (Comparable) method.invoke(o1);
            secondObject = (Comparable) method.invoke(o2);
        } catch (IllegalAccessException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (InvocationTargetException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (NoSuchMethodException e) {
            LOGGER.error(e.getMessage(), e);
        }

        if (firstObject == null) {
            return secondObject == null ? 0 : -1;
        }

        if (secondObject == null) {
            return 1;
        }

        return (isAscending ? 1 : -1) * firstObject.compareTo(secondObject);
    }
}
